var https = require("https");
var url = require("url");
var fs = require("fs");

var imgUrlArr = [
    "https://unsplash.com/?photo=67t2GJcD5PI",
    "https://unsplash.com/?photo=Rdsc2L517iQ",
    "https://unsplash.com/?photo=FgPGGFlY1gY"
];

var p1 = new Promise(function(resolve, reject){
    https.get(imgUrlArr[0], function(res){

        var imgData = "";
        
        res.setEncoding("binary");

        res.on("data", function(chunk){
            imgData += chunk;
        });

        res.on("end", function(chunk){
            fs.writeFile("test01.jpg", imgData, "binary", function(err){
                if(err){
                    console.log("download failed.");
                }else{
                    console.log("download success.");

                    resolve(imgUrlArr[0]);
                }
            });
        })

    });
});
var p2 = new Promise(function(resolve, reject){
    https.get(imgUrlArr[1], function(res){

        var imgData = "";
        
        res.setEncoding("binary");

        res.on("data", function(chunk){
            imgData += chunk;
        });

        res.on("end", function(chunk){
            fs.writeFile("test02.jpg", imgData, "binary", function(err){
                if(err){
                    console.log("download failed.");
                }else{
                    console.log("download success.");

                    resolve(imgUrlArr[0]);
                }
            });
        })

    });
});
var p3 = new Promise(function(resolve, reject){
    https.get(imgUrlArr[2], function(res){

        var imgData = "";
        
        res.setEncoding("binary");

        res.on("data", function(chunk){
            imgData += chunk;
        });

        res.on("end", function(chunk){
            fs.writeFile("test03.jpg", imgData, "binary", function(err){
                if(err){
                    console.log("download failed.");
                }else{
                    console.log("download success.");

                    resolve(imgUrlArr[0]);
                }
            });
        })

    });
});

var pa = Promise.all([p1, p2, p3]).then(function(dataArr){
    for (var i = 0; i < dataArr.length; i++) {
        var elem = dataArr[i];
        console.log(elem);
    }
})